package com.bite.blog.controller;

import com.bite.blog.Utils.JwtUtils;
import com.bite.blog.Utils.SecurityUtils;
import com.bite.blog.constants.Constant;
import com.bite.blog.model.BlogInfo;
import com.bite.blog.model.Result;
import com.bite.blog.model.UserInfo;
import com.bite.blog.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping ("/login")
    public Result login(String userName,String password){
        if(!StringUtils.hasLength(userName)||
            !StringUtils.hasLength(password)){
            return Result.fail("用户名或密码为空");
        }
        UserInfo userInfo = userService.queryByName(userName);
        if(userInfo==null||userInfo.getId()<0){
            return Result.fail("用户不存在");
        }
        if(!SecurityUtils.verify(password,userInfo.getPassword())){
           return Result.fail("密码错误");
        }
        Map<String,Object> claim = new HashMap<>();
        claim.put(Constant.USER_CLAIM_ID,userInfo.getId());
        claim.put(Constant.USER_CLAIM_NAME,userInfo.getUserName());
        return Result.success(JwtUtils.genToken(claim));
    }
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        String user_token = request.getHeader(Constant.USER_TOKEN_HEADER);
        Integer userId = JwtUtils.getUserIdFromToken(user_token);
        if(userId==null||userId<=0){
            return null;
        }
        UserInfo userInfo = userService.queryUserById(userId);
        userInfo.setPassword("");
        return userInfo;
    }
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        if(blogId==null||blogId<1){
            return null;
        }
        return userService.getAuthorByBlogId(blogId);
    }
}